import csv
from dbfread import DBF
import os
import sys
################################################################################
#
# config
# for file
# SOURCE_PATH = r'/home/fredyvia/dbf_data_solve/source/2016/道路附属设施.dbf'
# DEST_PATH = r"/home/fredyvia/dbf_data_solve/csv/2016/道路附属设施.csv"
#
# for dir
# SOURCE_PATH = r'/home/fredyvia/dbf_data_solve/source'
# DEST_PATH = r"/home/fredyvia/dbf_data_solve/csv"
#
################################################################################
SOURCE_PATH = r'/mnt/待处理POI/2017/公司企业.dbf'
DEST_PATH = r"/home/fredyvia/dbf_data_solve/csv/2017/公司企业.csv"
# config


def get_all_dbf(source_path, dest_path):
    res = []
    for fileName in os.listdir(source_path):
        source_file_path = source_path+os.sep+fileName
        if fileName.endswith(".dbf"):
            res.append(
                (source_file_path, os.path.splitext(dest_path+os.sep +
                                                    os.path.split(source_file_path)[-1])[0]+".csv"
                 )
            )
        elif os.path.isdir(source_file_path):
            res.extend(get_all_dbf(source_path+os.sep +
                       fileName, dest_path+os.sep+fileName))
    return res


def solve_file(source_file, dest_file):
    try:
        print("=======solving=======|"+source_file +
              "|=======save to======="+dest_file+"=======")
        dest_dir = os.path.dirname(dest_file)
        if not os.path.exists(dest_dir):
            os.makedirs(dest_dir)
        table = DBF(source_file, encoding="utf-8",
                    char_decode_errors="backslashreplace")
        writer = csv.writer(open(dest_file, 'w+'))
        writer.writerow(table.field_names)
        for record in table:
            writer.writerow(list(record.values()))
    except BaseException as e:
        print(e)
        print("unknown error")


def main(source_path, dest_path):
    if(os.path.isdir(source_path)):
        files = get_all_dbf(source_path, dest_path)
        # print(files)
        for source, dest in files:
            solve_file(source, dest)
    else:
        solve_file(source_path, dest_path)


if __name__ == "__main__":
    if len(sys.argv) == 1:
        main(SOURCE_PATH, DEST_PATH)
    elif len(sys.argv) == 3:
        main(sys.argv[1], sys.argv[2])
    else:
        print("error please specify source dir and desdir or modify this manually none")
